const GRID_SIZE = 4;
const CELL_SIZE = '15';
const CELL_GAP = '2';

export default class Grid {
    cells;
    constructor(gridElement: HTMLDivElement) {
        gridElement.style.setProperty("--grid-size", "" + GRID_SIZE);
        gridElement.style.setProperty("--cell-size", `${CELL_SIZE}vmin`);
        gridElement.style.setProperty("--cell-gap", `${CELL_GAP}vmin`);
        // 所有的cell单元格
        this.cells = createCellElements(gridElement).map((cellElements, index) => {
            return new Cell(cellElements, index % GRID_SIZE, Math.floor(index / GRID_SIZE))
        })
        console.log(this.cells);

    }


    get #emptyCells() {
        return this.cells.filter(cell => cell.tile == null);
    }
    randomEmptyCell() {
        const randomIndex = Math.floor(Math.random() * this.#emptyCells.length)
        return this.#emptyCells[randomIndex];
    }

    get cellsByColumn() {
        // @ts-ignore
        return Object.values(Object.groupBy(this.cells, cell => cell.x));
    }
    get cellsByRow() {
        // @ts-ignore
        return Object.values(Object.groupBy(this.cells, cell => cell.y));
    }
}

class Cell {
    #cellElement;
    x;
    y;
    #tile: any; //tile
    #mergeTile: any; //合并的tile
    constructor(cellElement: HTMLDivElement, x: number, y: number) {
        this.#cellElement = cellElement;
        this.x = x;
        this.y = y;
    }
    // 每个单元格可能会有tile
    get tile() {
        return this.#tile;
    }
    set tile(value) {
        this.#tile = value;
        if (value == null) {
            return
        }
        // 设置tile坐标
        this.#tile.x = this.x;
        this.#tile.y = this.y;
    }
    get mergeTile() {
        return this.#mergeTile
    }
    set mergeTile(value) {
        this.#mergeTile = value
        console.log(this.#mergeTile);
        
        if (value == null) {
            return
        }
        // 设置tile坐标
        this.#mergeTile.x = this.x;
        this.#mergeTile.y = this.y;
    }
    canAccept(tile: any) {
        return (this.tile == null || (this.tile.value === tile.value && this.mergeTile == null))
    }

    mergeTiles() {
        if (!(this.tile && this.mergeTile)) {
            return
        }
        
        this.tile.value = this.tile.value + this.mergeTile.value
        this.mergeTile.remove()
        this.mergeTile = null

    }
}
function createCellElements(gridElement: HTMLDivElement) {
    const cells = [];
    for (let i = 0; i < GRID_SIZE * GRID_SIZE; i++) {
        const cell = document.createElement("div");
        cell.classList.add("cell");
        cells.push(cell);
        gridElement.append(cell);
    }
    console.log(gridElement);

    return cells;
}